package com.wym.charging.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.JWTVerifier;
import lombok.extern.log4j.Log4j2;

import java.util.Date;
import java.util.Map;

/**
 * @author WangYimin 2024年12月25日 21:54:08
 */
@Log4j2
public class JwtUtil {
    private static final String SECRET_KEY = "your_secret_key";
    public static final long jwtExpirationMs = 60 * 1000 * 30;
    private static final Algorithm ALGORITHM = Algorithm.HMAC256(SECRET_KEY);
    private static final JWTVerifier verifier = JWT.require(ALGORITHM).build();

    public static String generateToken(Map<String, Object> claims) {
        return JWT.create()
                  .withClaim("claims", claims)
                  .withIssuedAt(new Date())
                  .withExpiresAt(new Date(System.currentTimeMillis() + jwtExpirationMs))
                  .sign(ALGORITHM);
    }

    public static Map<String, Object> parseToken(String token) {
        return verifier.verify(token).getClaim("claims").asMap();
    }

    // 验证JWT
    public boolean validateToken(String token) {
        try {
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            log.error("token错误: {}", e.getMessage());
            return false;
        }
    }
}